﻿using Spark.Config.SDK;
using System;
using System.Threading.Tasks;
using WebApiClient;

namespace Spark.Config
{
    public class RemoteConfigurationClient : IRemoteConfigurationClient
    {
        private readonly IRemoteConfigurationSource _remoteConfigSource;
        private readonly IConfigApi _apiClient;

        private DateTime _updateTime = DateTime.Now;

        public RemoteConfigurationClient(IRemoteConfigurationSource remoteConfigSource)
        {
            _remoteConfigSource = remoteConfigSource;
            //_apiClient = HttpApiClient.Create<IConfigApi>(_remoteConfigSource.Url);
            _apiClient = HttpApi.Create<IConfigApi>(_remoteConfigSource.Url);
        }

        public async Task<SDK.Config> GetConfig(bool reloading)
        {
            var query = new ConfigSearchRequest()
            {
                AppCode = _remoteConfigSource.AppCode,
                Key = _remoteConfigSource.Key
            };
            if (reloading)
            {
                query.UpdateTime = _updateTime;
            }
            var result = await _apiClient.GetLatestConfig(query);

            if (result?.Data != null && result?.IsSuccess == true)
            {
                _updateTime = result.Data.UpdateTime;
            }

            return await Task.FromResult(result?.Data);
        }
    }
}